from util.sqlite_util import conn, cursor
from entity.address import Address
from util.log_util import LogUtil
from typing import List
import random

class AddressDao:

    # 插入或更新
    @staticmethod
    def insertOrUpdate(addr :Address):
        try:
            if addr.id <= 0 :
                id = random.randint(1000000000,10000000000)
                addr.id = id
                cursor.execute('INSERT INTO address (id, province, city, district) VALUES (?, ?, ?, ?)', (addr.id, addr.province, addr.city, addr.disctrict))
                conn.commit()
            else :
                cursor.execute('UPDATE address SET province = ?, city = ?, district = ? where id = ?', (addr.province, addr.city, addr.district, addr.id))
                conn.commit()
        except Exception as e:
            LogUtil.error(f'>>> AddressDao insertOrUpdate 发生错误!\n{e}')
        else:
            LogUtil.error('>>> address:id{id} 更新成功!!!'.format(id=addr.id))
        finally:
            pass
    
    # 查询
    @staticmethod
    def query(province :str=None, city :str=None, district :str = None) -> List[Address]:
        sql = 'SELECT * FROM address where 1=1 '
        if province != None:
            sql += f" AND province LIKE '%{province}%' "
        if city != None:
            sql += f" AND city LIKE '%{city}%' "
        if district != None:
            sql += f" AND district LIKE '%{district}%' "
        
        try:
            cursor.execute(sql)
            result = [Address(row[0], row[1], row[2], row[3]) for row in cursor.fetchall()]
            return result
        except Exception as e:
            LogUtil.error(f'>>> AddressDao query 发生错误!\n{e}')
            return None